package com.heima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.pojo.dto.UserDto;
import com.heima.pojo.dto.UserQueryDto;
import com.heima.pojo.po.Role;
import com.heima.pojo.po.Users;
import com.heima.mapper.IUserMapper;
import com.heima.pojo.vo.PageVo;
import com.heima.pojo.vo.UserVo;
import com.heima.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 存折
 * @since 2024-10-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<IUserMapper, Users> implements IUserService {

    @Autowired
    private IUserMapper userMapper;
    @Override
    public PageVo<UserVo> query(UserDto userDto, UserQueryDto userQueryDto) {
        Page page = new Page<>(userQueryDto.getPageIndex(), userQueryDto.getPageSize());
        String userName = userQueryDto.getUserName();
        Page<Users> p = lambdaQuery().like(userName != null, Users::getUserName, userName)
                .page(page);
        long pages = p.getPages();
        long total = p.getTotal();
        List<Users> records = p.getRecords();
        List<Role> roleList= userMapper.getRole();

        List<UserVo> userVoList = new ArrayList<>();
        records.forEach(user -> {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            userVo.setRole(  roleList.stream().filter(r -> r.getRoleId().equals(userVo.getRoleId())).findFirst().get());
            userVoList.add(userVo);
        });
        return new PageVo<>(userQueryDto.getPageIndex(), userQueryDto.getPageSize(),pages,total,userVoList);
    }
}
